import json
import os
import threading
from tkinter import Button
from tkinter.ttk import Combobox

from util.comm.AsyncTask import AsyncTask
from util.comm.msg_util import msg
from util.comm.path import getPath
from util.database.cmd import run_cmd

class config_select:
    def __init__(self, tab, config_path=None):
        super().__init__()
        self.tab = tab
        if config_path is None or (not os.path.exists(config_path)):
            config_path = getPath()
            self.config_path = os.path.join(config_path, 'config.json')
        else:
            self.config_path = config_path

    def create(self, width=10):
        self.dropdown = Combobox(self.tab, width=width)
        self.load()
        self.dropdown.bind("<<ComboboxSelected>>", self.select_item)
        return self.dropdown

    def load(self):
        # 打开文件并读取JSON数据
        with open(self.config_path, 'r', encoding="utf-8") as file:
            data = json.load(file)
        drop_list = []
        drop_config_list = []
        if isinstance(data, list):
            for index, c in enumerate(data):
                drop_list.append(c['name'])
                drop_config_list.append(c)
        else:
            print(data)
        self.dropdown['values'] = drop_list
        self.config_list = drop_config_list
        self.dropdown.current(0)
        self.dropdown.config_info = drop_config_list[0]

    def select_item(self, event):
        index = self.dropdown.current()
        print('select_item----%s' % index)
        self.dropdown.config_info = self.config_list[index]

class select_reload_button:
    def __init__(self):
        super().__init__()

    def create(self, tab, config_select):
        self.tab = tab
        self.config_sync_flag = '0'
        button = Button(self.tab, text='↻', command=lambda s=config_select: self.change_config_sync(s))
        return button

    def change_config_sync(self, s):
        if hasattr(self, 'config_sync_flag') and self.config_sync_flag == '1':
            msg('已经打开配置文件,请勿重复操作')
            return
        self.config_sync_flag = '1'
        run_cmd(f"notepad {s.config_path}")
        s.load()
        self.config_sync_flag = '0'

class config_button:
    def __init__(self):
        super().__init__()
    def create(self, frame, tab, elements, config_path, refresh=False):
        self.win = frame
        self.tab = tab
        self.elements = elements
        self.config_path = config_path
        self.config_sync_flag = '0'
        button = Button(self.tab, text='⚙', command=lambda r=refresh: self.change_config_sync(r))
        return button
    def change_config_sync(self, r):
        if hasattr(self, 'config_sync_flag') and self.config_sync_flag == '1':
            msg('已经打开配置文件,请勿重复操作')
            return
        self.config_sync_flag = '1'
        AsyncTask(threading.Thread(target=self.change_config, args=(r,)), lambda : self.reset_sync()).execute_async()

    def reset_sync(self):
        self.config_sync_flag = '0'

    def change_config(self, refresh):
        run_cmd(f"notepad {self.config_path}")
        if refresh and hasattr(self, 'elements'):
            for element in self.elements:
                element.destroy()
            self.win.frame(self.tab)